package command;

import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * The Util to unit conversion
 * @author Jeff Zhuo
 *
 */
public class DataUnit {

	public enum Unit {
		B("B", 1), KB("KB", 2), MB("MB", 3), GB("GB", 4), TB("TB", 5);

		private int num;
		private String unit;

		private Unit(String unit, int num) {
			this.unit = unit;
			this.num = num;
		}

		@Override
		public String toString() {
			return String.valueOf(this.unit);
		}

		public String getUnit() {
			return unit;
		}

		public int getNum() {
			return num;
		}

	}

	/**
	 * Change size from Source unit to Target unit, 
	 * default maximum fraction digits is 4
	 * 
	 * @param size
	 * @param source Source unit
	 * @param target Target unit
	 * @return
	 */
	public static double unitConversion(double size, Unit source, Unit target) {
		return unitConversion(size, source, target, 4);
	}
	
	/**
	 * Change size from Source unit to Target unit, 
	 * 
	 * @param size
	 * @param source Source unit
	 * @param target Target unit
	 * @param maxFD maximum fraction digits
	 * @return
	 */
	public static double unitConversion(double size, Unit source, Unit target, int maxFD) {
		int minus = source.num - target.num;

		NumberFormat nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(maxFD);

		if (minus > 0) {
			size = size * (Math.pow(1024, minus));
		} else {
			minus = -minus;
			size = size / (Math.pow(1024, minus));
		}
		
		double result = Double.parseDouble(nf.format(size));

		return result;
	}
	
	/* byte -> other unit */
    public static String byteToUnit(Double data) {
        String stringData;

        DecimalFormat df = new DecimalFormat(".##");

        if (data < 1024d) {
            stringData = data + Unit.B.unit;
        } else if (data < Math.pow(1024, 2)) {
            stringData = df.format(data / 1024) + Unit.KB.unit;
        } else if (data < Math.pow(1024, 3)) {
            stringData = df.format(data / Math.pow(1024, 2)) + Unit.MB.unit;
        } else if (data < Math.pow(1024, 4)) {
            stringData = df.format(data / Math.pow(1024, 3)) + Unit.GB.unit;
        } else {
            stringData = df.format(data / Math.pow(1024, 4)) + Unit.TB.unit;
        }

        return stringData;
    }

}
